// 定义全局变量根据页面是否到底控制开关
let isbool
// 获取首页数据
function indexProduct() {
    $.ajax({
        type: 'GET',
        url: 'http://xiongmaoyouxuan.com/api/tab/1?start=0',
        headers: {
            'x-platform': 'pc'
        },
        success: function (data) {
            if (data.code == 200) {
                indexALL(data.data)
            }
        }
    })
}
// 动态渲染首页数据
function indexALL(data) {
    let indexHtmlTxt = template('indexTest', {
        data
    })
    $('#xmyxDesc').html(indexHtmlTxt)
    // 渲染商品列表
    showProductList(data.items.list)
    // 轮播图调用
    bannerSwiper()
    // 商品分类url获取
    getProductClassifyUrl()
    // 加载更多
    getMore()
    // 跳转到详情页
    jumpToDetails()
    // 点击log和首页刷新本页
    getIndexPage()
    // 切换板块url获取
    tabPageUrl()

}
let newProductList
// 渲染商品列表
function showProductList(data) {
    newProductList = data
    console.log('渲染的商品列表', data)
    let productListTxt = template('newProductList', {
        newProductList
    })
    $('#main .base-commodity-list').html(productListTxt)
    isbool = true
}


//搜索功能
$('.herder_search .searchBtn').on('click', function () {
    search()
})
//回车搜索
$('.herder_search input').bind('keydown', function (event) {
    var event = window.event || arguments.callee.caller.arguments[0];
    if (event.keyCode == 13) {
        search()
    }
})
//搜索功能
function search() {
    // 获取输入的搜索关键词
    let searchWord = $('.herder_search input').val()
    $.ajax({
        type: 'GET',
        url: 'https://www.xiongmaoyouxuan.com/api/search?',
        data: {
            word: searchWord,
        },
        success: function (data) {
            if (data.code == 200) {
                if (data.data.list.length == 0) {
                    alert(data.data.emptyMsg)
                } else {
                    $('.home .switchover').html('')
                    showProductList(data.data.list)
                    console.log(data.data)
                }
            } else {
                alert('出错了')
            }
        }
    })
}



// 商品分类url获取
function getProductClassifyUrl() {
    let ClassifyUrl
    let classifyindex = ''
    $('#main .classification_ul li').on('mouseover', function () {
        if ($(this).index() !== classifyindex) {
            classifyindex = $(this).index()
            switch ($(this).index()) {
                case 0:
                    ClassifyUrl = ['http://www.xiongmaoyouxuan.com/api/tab/2?start=0', 'http://www.xiongmaoyouxuan.com/api/tab/13?start=0']
                    break
                case 1:
                    ClassifyUrl = ['http://www.xiongmaoyouxuan.com/api/tab/5?start=0', 'http://www.xiongmaoyouxuan.com/api/tab/19?start=0']
                    break
                case 2:
                    ClassifyUrl = ['http://www.xiongmaoyouxuan.com/api/tab/3?start=0', 'http://www.xiongmaoyouxuan.com/api/tab/15?start=0']
                    break
                case 3:
                    ClassifyUrl = ['http://www.xiongmaoyouxuan.com/api/tab/4?start=0', 'http://www.xiongmaoyouxuan.com/api/tab/14?start=0']
                    break
                case 4:
                    ClassifyUrl = ['http://www.xiongmaoyouxuan.com/api/tab/10?start=0']
                    break
                case 5:
                    ClassifyUrl = ['http://www.xiongmaoyouxuan.com/api/tab/24?start=0']
                    break
                case 6:
                    ClassifyUrl = ['http://www.xiongmaoyouxuan.com/api/tab/6?start=0', 'http://www.xiongmaoyouxuan.com/api/tab/12?start=0']
                    break
                case 7:
                    ClassifyUrl = ['http://www.xiongmaoyouxuan.com/api/tab/16?start=0']
                    break
                case 8:
                    ClassifyUrl = ['http://www.xiongmaoyouxuan.com/api/tab/11?start=0', 'http://www.xiongmaoyouxuan.com/api/tab/7?start=0']
                    break
            }
            getProductClassify(ClassifyUrl)
        }
    })
}
// 加载商品分类显示
function getProductClassify(ClassifyUrl) {
    $('#main .classification .specificList .sidebar-panel-item1 ul').html(`<img src="../static/images/Spinner.gif" alt="">`)
    $('#main .classification .specificList .sidebar-panel-item2 ul').html('')
    // 第一项分类
    if (ClassifyUrl[0]) {
        $.ajax({
            type: 'GET',
            url: ClassifyUrl[0],
            success: function (data) {
                if (data.code == 200) {
                    firstClassify(data.data)
                }
            }
        })
        // 动态加载数据
        function firstClassify(data) {
            let indexHtmlTxt = template('womenWear', {
                data
            })
            $('#main .classification .specificList .sidebar-panel-item1 ul').html(indexHtmlTxt)
        }
    }

    // 第二项分类
    if (ClassifyUrl[1]) {
        $.ajax({
            type: 'GET',
            url: ClassifyUrl[1],
            success: function (data) {
                if (data.code == 200) {
                    secondClassify(data.data)
                }
            }
        })
        // 动态加载首页数据
        function secondClassify(data) {
            let indexHtmlTxt = template('womenShoes', {
                data
            })
            $('#main .classification .specificList .sidebar-panel-item2 ul').html(indexHtmlTxt)
        }
    }
}

// 轮播图
function bannerSwiper() {
    var mySwiper = new Swiper('.swiper-container', {
        loop: true, // 循环模式选项
        // grabCursor: true,
        effect: 'cube',
        // 如果需要分页器
        pagination: {
            el: '.swiper-pagination',
            clickable: true,
        },
        autoplay: true, //自动轮播
        // 如果需要前进后退按钮
        navigation: {
            nextEl: '.swiper-button-next',
            prevEl: '.swiper-button-prev',
        },
    })
}

// 加载更多
function getMore() {
    $('#choice-more .choice-more-btn').on('click', function () {
        // 移除'加载更多'按钮
        $('#choice-more .choice-more-btn').remove()
        // // 第一次点击'加载更多'按钮调用一次ajax
        more()
    })
}
//设置全局变量将页号为0
let pageNum = 0
//加载更多的url
let moreUrl

// 加载更多
function more() {
    //页号+20
    pageNum += 20
    $.ajax({
        type: 'GET',
        url: `http://www.xiongmaoyouxuan.com/api/tab/1/feeds?start=${pageNum}&sort=0`,
        success: function (data) {
            let shopList = data.data.list
            shopList = [
                ...newProductList,
                ...shopList
            ]
            // 重新渲染页面
            showProductList(shopList)
            // 启动滚动函数
            onscrollMore()
        }
    })
}
// 滚动加载更多
function onscrollMore() {
    $(window).scroll(function () {
        //isbool为true才执行
        if (isbool && scrollTop() + windowHeight() >= (documentHeight() - 300 /*滚动响应区域高度取200px*/ )) {
            isbool = false
            //页号+20
            pageNum += 20
            $.ajax({
                type: 'GET',
                url: `http://www.xiongmaoyouxuan.com/api/tab/1/feeds?start=${pageNum}&sort=0`,
                success: function (data) {
                    let moreList = data.data.list
                    shopList = [
                        ...newProductList,
                        ...moreList
                    ]
                    // 重新渲染页面
                    showProductList(shopList)
                }
            })
        }
    });
}
//获取页面顶部被卷起来的高度
function scrollTop() {
    return Math.max(
        //chrome
        document.body.scrollTop,
        //firefox/IE
        document.documentElement.scrollTop);
}
//获取页面文档的总高度
function documentHeight() {
    //现代浏览器（IE9+和其他浏览器）和IE8的document.body.scrollHeight和document.documentElement.scrollHeight都可以
    return Math.max(document.body.scrollHeight, document.documentElement.scrollHeight);
}
//获取页面浏览器视口的高度
function windowHeight() {
    //document.compatMode有两个取值。BackCompat：标准兼容模式关闭。CSS1Compat：标准兼容模式开启。
    return (document.compatMode == "CSS1Compat") ?
        document.documentElement.clientHeight :
        document.body.clientHeight;
}


// 跳转到详情页
function jumpToDetails() {
    $('#main .base-commodity-list').on('click', 'li', function () {
        let productID = $(this).attr('id')
        localStorage.setItem('PRODUCTID', productID)
        location.href = '../pages/detailPage.html'
        // console.log($(this).attr('id'))
    })
}
// 回到顶部按钮
function backTop() {
    $(document).on('scroll', function () {
        if ($(document).scrollTop() > 1400) {
            $('#backTopBtn').css(
                'display',
                'block'
            )
        } else {
            $('#backTopBtn').css(
                'display',
                'none'
            )
        }
        // console.log($(document).scrollTop())
    })
    // 点击时返回顶部
    $('#backTopBtn').on('click', function () {
        let height = $(document).scrollTop()
        let backTop = window.setInterval(function () {
            height = height - 50
            if (height <= 50) {
                $(document).scrollTop(0)
                window.clearInterval(backTop)
            }
            $(document).scrollTop(height)
        }, 5)
    })
}
// 跳转到首页
function getIndexPage() {
    $('#herder .herder_logo a').on('click', function () {
        location.reload()
    })
    $('#nav li[value=index]').on('click', function () {
        location.reload()
    })
}
//跳转到我的购物车
function toMycart() {
    $('#herder .myCart').on('click', function () {
        location.href = '../pages/carsList.html'
    })
}


// 调用获取首页数据
indexProduct()
//跳转到我的购物车
toMycart()
// 回到顶部按钮
backTop()


// 辨别切换板块的标题的url地址
function tabPageUrl() {
    let tabPageUrlList
    let tabPageindex = ''
    $('#nav ul li').on('click', function () {
        // 移除nav的样式
        $('#nav ul li').removeAttr('class')
        // 给点击的li添加选中样式
        $(this).addClass('active')
        // 如果点击的对象不是现在的对象，再执行
        if ($(this).index() !== tabPageindex) {
            tabPageindex = $(this).index()
            switch ($(this).index()) {
                case 1:
                    newProductList = ''
                    tabPageUrlList = ['http://www.xiongmaoyouxuan.com/api/column/29']
                    tabninePostage()
                    break
                case 2:
                    newProductList = ''
                    tabPageUrlList = ['http://www.xiongmaoyouxuan.com/api/column/170']
                    superLargePage()
                    break
                case 3:
                    newProductList = ''
                    tabPageUrlList = ['http://www.xiongmaoyouxuan.com/api/column/3183']
                    coldWerePage()
                    break

            }
            // getProductClassify(ClassifyUrl)
            //跳转到9块9包邮
            getPostageHeader(tabPageUrlList)
        }
    })
}
// 切换板块的标题
function getPostageHeader(tabPageUrlList) {
    pageNum = 0
    $.ajax({
        type: 'GET',
        url: tabPageUrlList[0],
        headers: {
            'x-platform': 'pc'
        },
        success: function (data) {
            if (data.code == 200) {
                tabPostageTitle(data.data)
            }
        }
    })
}
// 切换区域的头部
function tabPostageTitle(data) {
    let indexHtmlTxt = template('ninePostage', {
        data
    })
    $('.switchover').html(indexHtmlTxt)
}
// 9块9包邮
function tabninePostage() {
    $.ajax({
        type: 'GET',
        url: `http://www.xiongmaoyouxuan.com/api/sub_column/7/items?start=${pageNum}`,
        success: function (data) {
            let moreList = data.data.list
            shopList = [
                ...newProductList,
                ...moreList
            ]
            //页号+20
            pageNum += 20
            // 重新渲染页面
            showProductList(shopList)
        }
    })
}
// 超值大额券
function superLargePage() {
    $.ajax({
        type: 'GET',
        url: `http://www.xiongmaoyouxuan.com/api/sub_column/174/items?start=${pageNum}`,
        success: function (data) {
            let moreList = data.data.list
            shopList = [
                ...newProductList,
                ...moreList
            ]
            //页号+20
            pageNum += 20
            // 重新渲染页面
            showProductList(shopList)
        }
    })
}
// 降温急救穿搭
function coldWerePage() {
    $.ajax({
        type: 'GET',
        url: `http://www.xiongmaoyouxuan.com/api/column/3183/items?start=${pageNum}`,
        success: function (data) {
            let moreList = data.data.list
            shopList = [
                ...newProductList,
                ...moreList
            ]
            //页号+20
            pageNum += 20
            // 重新渲染页面
            showProductList(shopList)
        }
    })
}